import React, { useState } from 'react';
import { View, Text, StyleSheet, Modal, TouchableOpacity, Alert, ActivityIndicator, KeyboardAvoidingView, Platform, ScrollView, Keyboard, TouchableWithoutFeedback } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../constants/colors';
import InputField from './InputField';
import DateField from './DateField';
import GradientButton from './GradientButton';
import { bodyDataService } from '../services';
import { UserBodyDataBo } from '../types/api';

interface Props {
  visible: boolean;
  onClose: () => void;
  onComplete: () => void;
}

export default function PersonalInfoModal({ visible, onClose, onComplete }: Props) {
  const [height, setHeight] = useState('');
  const [weight, setWeight] = useState('');
  const [birthday, setBirthday] = useState('');
  const [saving, setSaving] = useState(false);

  const validateInputs = () => {
    if (!height.trim()) {
      Alert.alert('錯誤', '請輸入身高');
      return false;
    }

    if (!weight.trim()) {
      Alert.alert('錯誤', '請輸入體重');
      return false;
    }

    if (!birthday.trim()) {
      Alert.alert('錯誤', '請選擇出生日期');
      return false;
    }

    const heightNum = parseFloat(height);
    const weightNum = parseFloat(weight);

    if (isNaN(heightNum) || heightNum < 50 || heightNum > 250) {
      Alert.alert('錯誤', '請輸入有效的身高 (50-250cm)');
      return false;
    }

    if (isNaN(weightNum) || weightNum < 20 || weightNum > 300) {
      Alert.alert('錯誤', '請輸入有效的體重 (20-300kg)');
      return false;
    }

    return true;
  };

  const handleSave = async () => {
    if (!validateInputs()) {
      return;
    }

    setSaving(true);
    try {
      const bodyData: UserBodyDataBo = {
        height: parseFloat(height),
        weight: parseFloat(weight),
        birthday: birthday, // Already in YYYY-MM-DD format from DateField
      };

      await bodyDataService.saveOrUpdateBodyData(bodyData);
      
      Alert.alert('成功', '個人資料已保存', [
        { text: '確定', onPress: () => {
          onComplete();
          onClose();
        }}
      ]);
    } catch (error: any) {
      console.error('保存個人資料失敗:', error);
      Alert.alert('錯誤', error.message || '保存失敗，請稍後重試');
    } finally {
      setSaving(false);
    }
  };

  const handleSkip = () => {
    Alert.alert(
      '跳過設置',
      '跳過個人資料設置可能會影響AI健康顧問為您提供個性化建議的準確性。確定要跳過嗎？',
      [
        { text: '取消', style: 'cancel' },
        { text: '跳過', onPress: () => {
          onComplete();
          onClose();
        }}
      ]
    );
  };

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity onPress={onClose} style={styles.closeButton}>
            <Ionicons name="close" size={24} color={Colors.gray[600]} />
          </TouchableOpacity>
          <Text style={styles.title}>完善個人資料</Text>
          <TouchableOpacity onPress={handleSkip} style={styles.skipButton}>
            <Text style={styles.skipText}>跳過</Text>
          </TouchableOpacity>
        </View>

        <KeyboardAvoidingView
          style={styles.keyboardAvoidingView}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 20}
        >
          <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <ScrollView
              style={styles.scrollView}
              contentContainerStyle={styles.scrollContent}
              showsVerticalScrollIndicator={false}
              keyboardShouldPersistTaps="handled"
            >
              <View style={styles.description}>
                <Ionicons name="information-circle" size={24} color={Colors.primary} />
                <Text style={styles.descriptionText}>
                  為了讓AI健康顧問為您提供更準確的個性化建議，請填寫以下基本資料：
                </Text>
              </View>

              <View style={styles.form}>
                <View style={styles.formRow}>
                  <View style={{ flex: 1, marginRight: 8 }}>
                    <InputField
                      label="身高 (cm)"
                      value={height}
                      onChangeText={setHeight}
                      keyboardType="numeric"
                      placeholder="例如：170"
                      variant="card"
                    />
                  </View>
                  <View style={{ flex: 1, marginLeft: 8 }}>
                    <InputField
                      label="體重 (kg)"
                      value={weight}
                      onChangeText={setWeight}
                      keyboardType="numeric"
                      placeholder="例如：65"
                      variant="card"
                    />
                  </View>
                </View>

                <View style={{ marginTop: 16 }}>
                  <DateField
                    label="出生日期"
                    value={birthday}
                    onChange={setBirthday}
                    variant="card"
                  />
                </View>
              </View>

              <GradientButton
                title={saving ? "保存中..." : "完成設置"}
                onPress={handleSave}
                disabled={saving}
                style={styles.saveButton}
              />
            </ScrollView>
          </TouchableWithoutFeedback>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: Colors.gray[200],
  },
  closeButton: {
    padding: 8,
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: Colors.gray[800],
  },
  skipButton: {
    padding: 8,
  },
  skipText: {
    fontSize: 16,
    color: Colors.primary,
    fontWeight: '500',
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 16,
  },
  description: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    backgroundColor: Colors.gray[100],
    padding: 16,
    borderRadius: 12,
    marginBottom: 24,
  },
  descriptionText: {
    flex: 1,
    marginLeft: 12,
    fontSize: 14,
    lineHeight: 20,
    color: Colors.gray[700],
  },
  form: {
    flex: 1,
  },
  formRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  saveButton: {
    marginTop: 24,
    marginBottom: 20,
  },
});
